/* eslint-disable no-use-before-define */
/* eslint-disable no-tabs */
/** global react */
import { createHashHistory, createBrowserHistory } from 'history'
import axios from 'axios'
import { Modal } from 'antd'
import cloneDeep from 'clone-deep'
import { cache } from '@/utils'
import { logoutFun } from '@/utils/auth'
import config from '@/config'

const { mockPrefix, apiPrefix, baseURL, routerMode } = config

// 判断是否满足请求条件
const authApiURLs = ['/getTokenByTicket', '/logout']
const isCanRequest = (url: string) => {
  const isMockUrl = Boolean(apiPrefix.indexOf(mockPrefix) > -1)
  const LOCALtoken = cache.get('token')
  const isAuthURL = authApiURLs.includes(url)
  return isMockUrl ? true : LOCALtoken ? true : isAuthURL ? true : false
}
console.log(`******** baseURL: ${baseURL} ********`)
// 入参处理
const requestHandle = (options: any) => {
  const { method = 'POST', headers, url, data } = options

  if (isCanRequest(url)) {
    const cloneHeaders = cloneDeep(headers)
    const LOCALtoken = cache.get('token')
    const extendHeaders = LOCALtoken
      ? { 'Content-token': LOCALtoken, ...cloneHeaders }
      : cloneHeaders

    const isFullUrl = /^https?:\/\/.+/.test(url) // 全链接接口

    const reqURL = isFullUrl ? url : baseURL + apiPrefix + url

    const cloneData = cloneDeep(data)

    return axios({
      timeout: 7000,
      method: method.toUpperCase(),
      headers: extendHeaders,
      url: reqURL,
      data: cloneData,
    })
  } else {
    const error = new Error('不满足请求条件')
    return Promise.reject(error)
  }
}

// 响应正常处理
const responseNormalHanlde = (response: any) => {
  const { data, headers } = response
  switch (data.code) {
    case 2000:
      const SERVEtoken = headers['access-token'] || headers['Access-token']
      SERVEtoken && cache.set('token', SERVEtoken)
      return Promise.resolve(data)
    case 500:
    case 3000: // 第三方接口异常
    case 3001: // 参数无效
    case 4000: // xxx失败
    case 5000: // 系统异常
    case 5500: // 操作失败
      const error = new Error(data.msg ? data.msg : '无错误信息')
      return Promise.reject(error)
    case 403:
    case 4003:
      console.log('未授权')
      const history =
        routerMode === 'browser' ? createBrowserHistory() : createHashHistory()
      history.push('/no-auth')
      return Promise.reject()

    default:
      const unknown_error = new Error(data.msg ? data.msg : '系统未知错误！')
      return Promise.reject(unknown_error)
  }
}

// 响应异常处理
const responseErrorHanlde = ({ status, data }: any) => {
  switch (status) {
    case 401:
      Modal.error({
        title: '登录状态过期,请重新登录！',
        onOk: () => logoutFun(),
      })
      break
    default:
      Modal.error({
        title: data.message || '系统异常,请重新登录！',
        onOk: () => logoutFun(),
      })
      break
  }

  return Promise.reject()
}

export default function request(options: any) {
  return requestHandle(options)
    .then((response) => responseNormalHanlde(response))
    .catch((error) => {
      console.log('-----------response error:-----------')
      console.log(error.response)
      return error.response
        ? responseErrorHanlde(error.response)
        : Promise.reject(error)
    })
}
